package com.fujin.gulimall.ware.service.impl;

import com.fujin.common.constant.WareConstant;
import com.fujin.gulimall.ware.Vo.MergeVo;
import com.fujin.gulimall.ware.Vo.PurchaseDoneItemVo;
import com.fujin.gulimall.ware.Vo.PurchaseDoneVo;
import com.fujin.gulimall.ware.entity.PurchaseDetailEntity;
import com.fujin.gulimall.ware.service.PurchaseDetailService;
import com.fujin.gulimall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fujin.common.utils.PageUtils;
import com.fujin.common.utils.Query;

import com.fujin.gulimall.ware.dao.PurchaseDao;
import com.fujin.gulimall.ware.entity.PurchaseEntity;
import com.fujin.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Override
    public void purchaseMerge(MergeVo mergeVo) {
        //两种情况
        //purchaseId为空时创建新的采购单
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());

            this.save(purchaseEntity);

            purchaseId = purchaseEntity.getId();
        }

        //不为空的时候直接保存采购单信息
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setCreateTime(new Date());
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(finalPurchaseId);

    }

    @Override
    public void purchaseReceived(List<Long> purchaseIds) {
        //1、判断传入的采购单是否为新建或已分配的状态
        //将新建或已分配过滤出来 并修改状态为"已领取"
        List<PurchaseEntity> collect = purchaseIds.stream().map(item -> {
            PurchaseEntity entity = this.baseMapper.selectById(item);
            return entity;
        }).filter(p -> {
            if (p.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    p.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、改变采购单状态
        this.updateBatchById(collect);

        //3、改变采购项状态
        collect.forEach(item -> {
            List<PurchaseDetailEntity> purchaseDetails = purchaseDetailService.list(
                    new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", item.getId()));

            List<PurchaseDetailEntity> collect1 = purchaseDetails.stream().map(p -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(p.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });

    }

    @Transactional
    @Override
    public void PurchaseDone(PurchaseDoneVo purchaseDoneVo) {
        //1、修改采购项状态
        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        //判断采购是否成功
        boolean flag = true;
        List<PurchaseDetailEntity> list = new ArrayList();
        for (PurchaseDoneItemVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                //采购成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //采购成功后 入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getSkuNum(),entity.getWareId());
            }
            list.add(detailEntity);
        }
        //保存采购项信息
        purchaseDetailService.updateBatchById(list);

        //2、修改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}